﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
using ModbusTestTool.Singeltons;

namespace ModbusTestTool.UI
{
    public partial class FileSelectControl : UserControl
    {
          public BindingList<fileSelect> storage;


          DataGridViewComboBoxColumn DropMenu;


        public FileSelectControl()
        {

            InitializeComponent();


            this.DragEnter += new DragEventHandler(FileSelector_DragEnter);
            this.DragDrop += new DragEventHandler(FileSelector_DragDrop);

            dataGridView1.DragEnter += new DragEventHandler(FileSelector_DragEnter);
            dataGridView1.DragDrop += new DragEventHandler(FileSelector_DragDrop);

            if (File.Exists("out.xml"))
            {
                using (StreamReader temp = new StreamReader("out.xml"))
                {
                    XmlSerializer outHandle = new XmlSerializer(typeof(BindingList<fileSelect>));
                    storage = (BindingList<fileSelect>)outHandle.Deserialize(temp);
                }
            }
            else
            {
                storage = new BindingList<fileSelect>();
            }

            //dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
            
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.AutoSize = false;
            dataGridView1.DataSource = storage;
            
            DataGridViewColumn filename = new DataGridViewTextBoxColumn();
            filename.Name = "File Name";
            filename.ReadOnly = false;
            filename.DataPropertyName = "filename";
            
            dataGridView1.Columns.Add(filename);


            DataGridViewColumn pollTime = new DataGridViewTextBoxColumn();
            pollTime.Name = "Poll Time";
            pollTime.ReadOnly = false;
            pollTime.DataPropertyName = "pollRate";
            dataGridView1.Columns.Add(pollTime);

            DataGridViewColumn ModbusIdColumn = new DataGridViewTextBoxColumn();
            ModbusIdColumn.Name = "Modbus ID";
            ModbusIdColumn.ReadOnly = false;
            ModbusIdColumn.DataPropertyName = "modbusId";
            dataGridView1.Columns.Add(ModbusIdColumn);


           DropMenu = new DataGridViewComboBoxColumn();
            //dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
            DropMenu.Name = "Tag";
            
            //DropMenu.ReadOnly = true;
            
            DropMenu.DataSource = SettingsSingelton.Instance.getListState();
            DropMenu.ValueType = typeof(string); ;
            
            
            dataGridView1.Columns.Add(DropMenu);
            //OpenButton.Text = "Start";
            //OpenButton.UseColumnTextForButtonValue = true;




            DataGridViewButtonColumn OpenButton = new DataGridViewButtonColumn();
            dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
            OpenButton.Name = "Open File";
            OpenButton.ReadOnly = true;
            OpenButton.Text = "Start";
            OpenButton.UseColumnTextForButtonValue = true;
            //outputfilenameColumn.DataPropertyName = "outputfile";
            dataGridView1.Columns.Add(OpenButton);

            for (int i = 0; i < dataGridView1.RowCount && i < storage.Count; i++)
            {
                DataGridViewComboBoxCell cell = dataGridView1[3, i] as DataGridViewComboBoxCell;
                if (storage[i].tag != null || storage[i].tag != string.Empty)
                {
                    cell.Value = "tag1";
                }
 
            }

            //this.AutoSize = true;

            dataGridView1.EditingControlShowing += DGV_EditingControlShowing;
            dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);

            SettingsSingelton.Instance.NewStateChanged += new SettingsSingelton.NewStateHandler(Instance_NewStateChanged);
        }

        void Instance_NewStateChanged(object sender, NewStateEvenArgs data)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    DropMenu.DataSource = null;
                    
                    DropMenu.DataSource = data.values;
                }
                ));
            }
            else
            {
                DropMenu.DataSource = data.values;
            }
            
        }

        void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 3)
            {
                if(e.RowIndex < storage.Count)
                    e.Value = storage[e.RowIndex].tag;
            }
   
        }
        /// <summary>
        /// Wierd way to get the value changed in combox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (dataGridView1.CurrentCell.ColumnIndex == 3 && e.Control is ComboBox)
            {
                ComboBox comboBox = e.Control as ComboBox;
                comboBox.SelectedIndexChanged += LastColumnComboSelectionChanged;
            }
        }

        private void LastColumnComboSelectionChanged(object sender, EventArgs e)
        {
            Console.WriteLine(((System.Windows.Forms.DataGridViewComboBoxEditingControl)(sender)).EditingControlFormattedValue as string);
            storage[((System.Windows.Forms.DataGridViewComboBoxEditingControl)(sender)).EditingControlRowIndex].tag = 
                (String) ((System.Windows.Forms.DataGridViewComboBoxEditingControl)(sender)).EditingControlFormattedValue;
        }





        void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 3)
            {
                storage[e.RowIndex].tag = dataGridView1[e.ColumnIndex, e.RowIndex].Value as string;
            }
        }

        /// <summary>
        /// This function defines where to click to start the box launching process
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (e.ColumnIndex == 4)
            //{
               
            //    Settings.Instance.openPort();
            //    //MessageBox.Show(dataGridView1[0,e.RowIndex].Value.ToString());   
            //    ParamWindows window = new ParamWindows(Settings.Instance.State.modbusId, Settings.Instance.master, dataGridView1[0, e.RowIndex].Value.ToString(),
            //        "none.txt", Int32.Parse(dataGridView1[1, e.RowIndex].Value.ToString()));
            //    window.Show();
            //}

            //This is the new way to launch the monitoring windows using tagging
            if (e.ColumnIndex == 4)
            {

                //Settings.Instance.openPort();
                //MessageBox.Show(dataGridView1[0,e.RowIndex].Value.ToString());  
               
                
                string tagName = ((dataGridView1[3, e.RowIndex] as DataGridViewComboBoxCell).EditedFormattedValue) as string;

                if (tagName == string.Empty)
                    return;
                
                ModbusTestTool.Singeltons.state stateToHandle = SettingsSingelton.Instance.getState(tagName);
                
                stateToHandle.Initialize();
                try
                {
                    stateToHandle.openPort();
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                    Error_Logging.ErrorLog.Instance.addMessage(err.Message);
                    return;
                }

                ParamWindows window = new ParamWindows(byte.Parse(dataGridView1[2,e.RowIndex].Value.ToString()), stateToHandle.master, dataGridView1[0, e.RowIndex].Value.ToString(), "none.txt",
                                       Int32.Parse(dataGridView1[1, e.RowIndex].Value.ToString()));
                
                //ParamWindows window = new ParamWindows(SettingsSingelton.Instance.getState(dataGridView1[3,e.RowIndex].Value, Settings.Instance.master, dataGridView1[0, e.RowIndex].Value.ToString(),
                 //   "none.txt", Int32.Parse(dataGridView1[1, e.RowIndex].Value.ToString()));
                window.Show();
            }


        }

        void dataGridView1_Click(object sender, DataGridViewCellEventArgs  e)
        {
          
        }

        void FileSelector_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                foreach (string item in files)
                {
                    storage.Add(new fileSelect(item, 100));
                }
            }
            catch (Exception err)
            {
                Error_Logging.ErrorLog.Instance.addMessage(err.Message);
                MessageBox.Show("Make sure you are not editing something");
                MessageBox.Show(err.Message);
            }
        }

        void FileSelector_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
                e.Effect = DragDropEffects.All;
        }

        void FileSelector_FormClosing(object sender, FormClosingEventArgs e)
        {
            //XmlSerializer outHandle = new XmlSerializer(typeof(BindingList<fileSelect>));
            saveFileList();
            
        }

        private void saveFileList()
        {
            using (StreamWriter temp = new StreamWriter("out.xml"))
            {
                XmlSerializer outHandle = new XmlSerializer(typeof(BindingList<fileSelect>));
                outHandle.Serialize(temp, storage);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            saveFileList();
        }

        private void Save_Click(object sender, EventArgs e)
        {
            saveFileList();
        }
    }

    public class fileSelect
    {
        public fileSelect()
        {
            filename = "";
            _pollRate = 100;
        }

        public fileSelect(string infilename, int inpollRate)
        {
            filename = infilename;
            _pollRate = inpollRate;
        }
        public string modbusId { set; get; }
        public string filename { set; get; }
        public string tag { set; get; }
        private int _pollRate;
        public string pollRate
        {
            set
            {
                _pollRate = int.Parse(value);
            }
            get
            {
                return _pollRate.ToString();
            }
        }

        public string port { set; get; }
    }
    
}
